package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.UserConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmAuditNewsDao;
import com.heima.model.wemedia.dao.AdWmNewsDao;
import com.heima.model.wemedia.dtos.AdWmNewsDto;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmTaskService;
import com.heima.wemedia.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialService wmMaterialService;
    @Resource
    private WmNewsMaterialMapper newsMaterialMapper;
    @Autowired
    private AutoScanService autoScanService;
    @Autowired
    private WmTaskService taskService;

    @Autowired
    private IArticleClient iArticleClient;


    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmChannelService wmChannelService;

    @Override
    public ResponseResult list(WmNewsPageReqDto reqDto) {
        //参数校验
        reqDto.checkParam();

        IPage page = new Page(reqDto.getPage(), reqDto.getSize());
        //构造查询参数
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.get().getId());
        queryWrapper.eq(reqDto.getStatus() != null, WmNews::getStatus, reqDto.getStatus());

        queryWrapper.eq(reqDto.getChannelId() != null, WmNews::getChannelId, reqDto.getChannelId());
        queryWrapper.like(!StringUtils.isEmpty(reqDto.getKeyword()), WmNews::getTitle, reqDto.getKeyword());

        if (reqDto.getBeginPubDate() != null && reqDto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getCreatedTime, reqDto.getBeginPubDate(), reqDto.getEndPubDate());
        }
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page, queryWrapper);

        ResponseResult result = new PageResponseResult(reqDto.getPage(), reqDto.getSize(), (int) page.getTotal());

        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //参数校验
        checkParam(wmNewsDto);
        //修改或者保存
        WmNews wmNews = saveOrUpdate(wmNewsDto);
        if(wmNews.getStatus() == WmNews.Status.NORMAL.getCode()){
            return ResponseResult.okResult(null);
        }
        //获取正文中所有的图片
        List<String> pics = getPictures(wmNewsDto.getContent());
        saveRelations(pics, wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);

        saveRelationsByCover(pics,wmNewsDto,wmNews);
//        if(wmNews.getPublishTime() != null){
//            taskService.addTask(wmNews);
//        }else{
            autoScanService.scan(wmNews.getId());
//        }

        return ResponseResult.okResult(null);
    }

    /**
     * 自媒体端自媒体文章人工审核的审核失败
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        // 校验参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // select * from wm_news
        // where userid = ?
        // 用MybatisPlus进行条件查询
        WmNews wmNews = getById(dto.getId());
        // 判断自媒体新闻表是否为空
        if (wmNews == null){
            // 为空返回对象不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 添加拒绝原因
        wmNews.setReason(dto.getMsg());
        // 修改审核状态
        wmNews.setStatus(UserConstants.NOT_PASS);
        // 更新自媒体新闻表
        updateById(wmNews);
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 自媒体端自媒体文章人工审核的审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        // 1. g根据newsid 拿到 news
        // 2. 根据channelId拿到channel name
        // 3. 根据news.userId 拿到 author信息
        // 5. createtime


        // 校验参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // select * from wm_news
        // where userid = ?
        // 用MybatisPlus进行条件查询
        WmNews wmNews = getById(dto.getId());
        // 判断自媒体新闻表是否为空
        if (StringUtils.isEmpty(wmNews) && wmNews.getStatus()!=3 ) {
            // 为空返回对象不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 修改审核状态
        wmNews.setStatus(UserConstants.PONSER_EXAMINE_PASS);

        // 获取文章新闻id
        Integer wnNewsID = dto.getId();

        // 根据文章id查询表
        WmNews news = getById(wnNewsID);

        Integer userId = news.getUserId();

        WmUser wmUser = wmUserService.getById(userId);

        //获取作者名字
        String userName = wmUser.getName();

        //获取频道名字
        WmChannel wmChannel = wmChannelService.getById(news.getChannelId());
        String channelName = wmChannel.getName();


        ArticleDto articleDto = new ArticleDto();

        BeanUtils.copyProperties(news,articleDto);

        articleDto.setChannelName(channelName);
        articleDto.setAuthorName(userName);
        articleDto.setAuthorId(news.getUserId());

        ResponseResult result = iArticleClient.saveArticle(articleDto);
        Object data = result.getData();

        news.setArticleId((Long) data);
        save(news);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 对要进行人工审核的文章的列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list_vo(AdWmNewsDto dto) {

            log.info("接受道的dto----{}",dto);

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        IPage<AdWmNewsDao> daoPage = new Page<>();

        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus()!=0) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if (!StringUtils.isEmpty(dto.getTitle())) {
            queryWrapper.like(WmNews::getTitle, dto.getTitle());
        }

        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page,queryWrapper);


        BeanUtils.copyProperties(page,daoPage,page.getRecords().toString());


        ArrayList<AdWmNewsDao> list = new ArrayList<>();


        page.getRecords().stream().forEach( itm -> {

            AdWmNewsDao adWmNewsDao = new AdWmNewsDao();

            BeanUtils.copyProperties(itm,adWmNewsDao);

            WmUser wmUser = wmUserService.getById(itm.getUserId());

            adWmNewsDao.setAuthorName(wmUser == null? null:wmUser.getName());

            list.add(adWmNewsDao);
        });

        daoPage.setRecords(list);



        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) daoPage.getTotal());

        result.setData(daoPage.getRecords());

        return result;
    }

    /**
     * 根据id查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult one_vo(int id) {
        if(StringUtils.isEmpty(id)){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询得到信息
        WmNews wmNews = this.getById(id);
        WmAuditNewsDao wmAuditNewsDao = new WmAuditNewsDao();
        //将信息复制到wmAuditNewsDao
        BeanUtils.copyProperties(wmNews,wmAuditNewsDao);
        //根据文章表的用户id得到用户信息
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        if (wmUser == null) {
            wmAuditNewsDao.setAuthorName("未知");
        }else{
            wmAuditNewsDao.setAuthorName(wmUser.getName());
        }
        return ResponseResult.okResult(wmAuditNewsDao);
    }


    /**
     * 封面和素材的关系
     *
     * @param pics
     * @param newsDto
     * @param wmNews
     */
    private void saveRelationsByCover(List<String> pics,WmNewsDto newsDto,WmNews wmNews){
        List<String> images = newsDto.getImages();
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(newsDto.getType())){
            int size = pics.size();
            if(size >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = pics.stream().limit(3).collect(Collectors.toList());
            }else if(size >= 1 && size < 3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = pics.stream().limit(1).collect(Collectors.toList());
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if(!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(StringUtils.collectionToCommaDelimitedString(images));
            }
            updateById(wmNews);
        }

        if(!CollectionUtils.isEmpty(images)){
            saveRelations(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }


    /**
     * 保存素材和文章的关系
     *
     * @param pics
     * @param newsId
     */
    private void saveRelations(List<String> pics,Integer newsId,Short type){
        if(CollectionUtils.isEmpty(pics)){
            return;
        }
        List<WmMaterial> list = wmMaterialService.list(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, pics));
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        List<Integer> ids = list.stream().map(WmMaterial::getId).collect(Collectors.toList());
        newsMaterialMapper.saveRelations(ids,newsId,type);
    }


    /**
     * 从正文中获取图片素材
     *
     * @param content
     * @return
     */
    private List<String> getPictures(String content){
        List<String> pics = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(content,Map.class);
        for(Map map : mapList){
            if("image".equals(map.get("type"))){
                pics.add((String)map.get("value"));
            }
        }
        return pics;
    }


    /**
     * 保存或者修改文章
     *
     * @param wmNewsDto
     * @return
     */
    private WmNews saveOrUpdate(WmNewsDto wmNewsDto){
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,news);
        news.setUserId(WmThreadLocalUtil.get().getId());
        //封面图片转换aaa.jpg,bb.jpg
        if(!CollectionUtils.isEmpty(wmNewsDto.getImages())){
            news.setImages(StringUtils.collectionToCommaDelimitedString(wmNewsDto.getImages()));
        }
        news.setCreatedTime(new Date());
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())){
            news.setType(null);
        }
        if(wmNewsDto.getId() == null){
            save(news);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNewsDto.getId()));
            updateById(news);
        }

        return news;
    }

    /**
     * 参数校验
     *
     * @param newsDto
     */
    private void checkParam(WmNewsDto newsDto){
        if(StringUtils.isEmpty(newsDto.getTitle())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(StringUtils.isEmpty(newsDto.getContent())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
